package org.happen.android.ui;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.happen.android.R;
import org.happen.android.base.AppActivity;
import org.happen.android.base.BaseLvAdapter;
import org.happen.android.bean.BaseRequest;
import org.happen.android.bean.request.exts.MainReq;
import org.happen.android.bean.response.JsonObjResponse;
import org.happen.android.bean.response.JsonStrResponse;
import org.happen.android.bean.response.exts.MainResp;
import org.happen.android.bean.response.exts.MainResp.MessageItem;
import org.happen.android.core.net.AppRequestManager;
import org.happen.android.core.net.OnRequestCallback2;
import org.happen.android.ui.widget.SelectArgs;
import org.happen.android.ui.widget.SelectListWidget;
import org.happen.android.ui.widget.SelectListWidget.OnSelectCallback;
import org.happen.android.widget.PopupDialog;
import org.happen.android.widget.PullToRefreshWidget;
import org.happen.android.widget.PullToRefreshWidget.OnFooterRefreshListener;
import org.happen.android.widget.PullToRefreshWidget.OnHeaderRefreshListener;
import org.liushui.mycommons.android.annotation.OnClick;
import org.liushui.mycommons.android.annotation.ViewInject;
import org.liushui.mycommons.android.annotation.helper.InjectHelper;
import org.liushui.mycommons.android.log.McLog;

import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppActivity
{

	static final int REQ_CAMERA = 101;
	static final int REQ_CARP = 102;
	static final int REQ_SEND = 103;

	@ViewInject(R.id.btn_title1)
	View btnLeft;
	@ViewInject(R.id.btn_title2)
	View btnRight;
	@ViewInject(R.id.tv_title1)
	TextView tvTitle1;
	@ViewInject(R.id.tv_title2)
	TextView tvTitle2;
	@ViewInject(R.id.listview)
	ListView listview;
	@ViewInject(R.id.ptrw)
	PullToRefreshWidget pullToRefreshWidget;
	@ViewInject(R.id.rl_title)
	View llTitle;

	JsonObjResponse<MainResp> mainJsonObjResponse;
	LvAdapter adapter;

	Handler handler;
	int currentLeftIdx = 0;
	int currentRightIdx = 0;

	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main3);

		init();

		doRequest();
	}

	void init()
	{
		InjectHelper.init(this, this);
		handler = new Handler();
		adapter = new LvAdapter();
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(adapter);

		pullToRefreshWidget.setOnFooterRefreshListener(new OnFooterRefreshListener() {
			public void onFooterRefresh(PullToRefreshWidget view)
			{
				handler.postDelayed(new Runnable() {
					public void run()
					{
						pullToRefreshWidget.onFooterRefreshComplete();
						adapter.notifyDataSetChanged();
					}
				}, 1000);
			}
		});

		pullToRefreshWidget.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
			public void onHeaderRefresh(PullToRefreshWidget view)
			{
				handler.postDelayed(new Runnable() {
					public void run()
					{
						pullToRefreshWidget.onHeaderRefreshComplete();
						adapter.notifyDataSetChanged();
					}
				}, 1000);
			}
		});
		tvTitle1.setOnClickListener(onClickListener);
		tvTitle2.setOnClickListener(onClickListener);
	}

	@OnClick({ R.id.btn_title1, R.id.btn_title2 })
	OnClickListener onClickListener = new OnClickListener() {
		public void onClick(View v)
		{
			String data[] = null;
			int idx = 0;
			switch (v.getId())
			{
				case R.id.btn_title1:

					break;
				case R.id.btn_title2:
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "/temp.jpg")));
					startActivityForResult(intent, REQ_CAMERA);
					break;
				case R.id.tv_title1:
					data = new String[] { "全国", "5公里", "50公里", "500米" };
					idx = currentLeftIdx;
					doShowDialog(idx, data, true);
					break;
				case R.id.tv_title2:
					data = new String[] { "24小时", "最新", "本周", "全部" };
					idx = currentRightIdx;
					doShowDialog(idx, data, false);
					break;
			}
		}
	};

	void doShowDialog(int idx, String data[], final boolean isLeft)
	{
		PopupDialog dialog = new PopupDialog(tvTitle1, this, true);
		SelectArgs args = new SelectArgs();
		args.index = idx;
		SelectListWidget widget = new SelectListWidget(context, args);
		widget.setData(data);
		widget.setOnSelectListCallback(new OnSelectCallback() {
			public void onCallback(SelectArgs args)
			{
				if (isLeft)
				{
					currentLeftIdx = args.index;
					tvTitle1.setText(args.obj);
				} else
				{
					currentRightIdx = args.index;
					tvTitle2.setText(args.obj);
				}
			}
		});
		widget.init();
		dialog.setContentView(widget, -1, -2);
		dialog.setDismissOnTouchOuter(true);
		Rect r = new Rect();
		llTitle.getGlobalVisibleRect(r);
		dialog.show(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, r.bottom);
	}

	void doRequest()
	{
		MainReq mainReq = new MainReq();

		AppRequestManager.getInstance().doGet(mainReq, new OnRequestCallback2() {
			public void onJsonResponse(BaseRequest request, JsonStrResponse jsonResponse)
			{
				if (jsonResponse.isSuccess())
				{
					mainJsonObjResponse = JsonObjResponse.newInstance(MainResp.class, jsonResponse);
					McLog.i("mainJsonObjResponse = " + mainJsonObjResponse);
					adapter.notifyDataSetChanged();
				}
			}
		});
	}

	class LvAdapter extends BaseLvAdapter
	{

		public int getCount()
		{
			if (mainJsonObjResponse == null)
			{
				return 0;
			}
			if (mainJsonObjResponse.jsonObj == null)
			{
				return 0;
			}
			return mainJsonObjResponse.jsonObj.messages.length;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			ViewHolder vh = new ViewHolder();
			if (convertView == null)
			{
				convertView = View.inflate(context, R.layout.item_main_lv, null);
				InjectHelper.init(vh, convertView);
				convertView.setTag(vh);
			} else
			{
				vh = (ViewHolder) convertView.getTag();
			}
			MessageItem item = mainJsonObjResponse.jsonObj.messages[position];
			vh.tvName.setText(item.userId + "");
			vh.tvLocal.setText(item.messageAddress);
			vh.tvContent.setText(item.messageContent);
			vh.tvTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(item.messageTime.time)));

			vh.tvCuo.setText(item.messageDown + "");
			vh.tvZan.setText(item.messageUp + "");
			return convertView;
		}

		public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
		{
			Intent it = new Intent(context, DetailActivity.class);
			startActivity(it);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
			case REQ_CAMERA:
			{
				if (resultCode == RESULT_OK)
				{
					// 设置文件保存路径这里放在跟目录下
					File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");

					Intent intent = new Intent("com.android.camera.action.CROP");
					intent.setDataAndType(Uri.fromFile(picture), "image/*");
					intent.putExtra("crop", "true");
					// aspectX aspectY 是宽高的比例
					intent.putExtra("aspectX", 1);
					intent.putExtra("aspectY", 1);
					// outputX outputY 是裁剪图片宽高
					// intent.putExtra("outputX", 200);
					// intent.putExtra("outputY", 200);
					intent.putExtra("return-data", true);
					// startActivityForResult(intent, REQ_CARP);

					startActivity(new Intent(context, SendActivity.class));
				}
				break;
			}
			case REQ_CARP:// 处理结果
			{
				if (resultCode == RESULT_OK)
				{
					Bundle extras = data.getExtras();
					if (extras != null)
					{
						// Bitmap photo = extras.getParcelable("data");
					}
				}
				break;
			}
		}
	}
}

class ViewHolder
{
	@ViewInject(R.id.tv_name)
	TextView tvName;
	@ViewInject(R.id.tv_content)
	TextView tvContent;
	@ViewInject(R.id.tv_item_local)
	TextView tvLocal;
	@ViewInject(R.id.tv_item_time)
	TextView tvTime;
	@ViewInject(R.id.tv_zan)
	TextView tvZan;
	@ViewInject(R.id.tv_cuo)
	TextView tvCuo;
	@ViewInject(R.id.tv_more)
	TextView tvMore;
	@ViewInject(R.id.tv_comment)
	TextView tvComment;
}